package com.example.securitysample.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import javax.sql.DataSource;

/**
 * @author TonySong
 * @date 2024/5/28 0028
 * @time 15:11
 */
@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Resource
    private MyAccessDeins myAccessDeins;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests( (auth) ->{
            //放过登录请求
            auth.requestMatchers("/login").permitAll();
            //admin下的资源必须是ADMIN角色可以访问
            //auth.requestMatchers("/admin/**").hasRole("ADMIN");
            auth.requestMatchers("/admin/**","/user/**").hasRole("ADMIN");
            //user下的资源必须是USER角色可以访问
            auth.requestMatchers("/user/**").hasRole("USER");
            //任何请求都要进行认证
            auth.anyRequest().authenticated();
        });

        http.formLogin(form ->
                form.loginPage("/login").permitAll()
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/index")
        );
        //403的处理请求 url
        //http.exceptionHandling().accessDeniedPage("/403");
        //403的json处理
        http.exceptionHandling().accessDeniedHandler(this.myAccessDeins);

        http.csrf(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource){
        return new JdbcUserDetailsManager(dataSource);
         //基于内存的配置
//        UserDetails u1 = User.withUsername("user").password("1234").roles("user").build();
//        UserDetails u2 = User.withUsername("admin").password("1234").roles("admin").build();
//        return new InMemoryUserDetailsManager(u1,u2);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //不使用密码加密规则的实现
        return NoOpPasswordEncoder.getInstance();
    }
}
